package com.kotlin.tsw.kotlinmall.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.kotlin.base.utils.AppPrefsUtils
import com.kotlin.tsw.baselibrary.ext.loadUrl
import com.kotlin.tsw.baselibrary.ui.fragment.BaseFragment
import com.kotlin.tsw.kotlinmall.R
import com.kotlin.tsw.kotlinmall.ui.activity.SettingActivity
import com.kotlin.tsw.providerlibrary.common.ProviderConstant
import com.kotlin.tsw.providerlibrary.common.isLogined
import com.kotlin.tsw.usercenter.ui.activity.LoginActivity
import com.kotlin.tsw.usercenter.ui.activity.RegisterActivity
import com.kotlin.tsw.usercenter.ui.activity.UserInfoActivity
import kotlinx.android.synthetic.main.fragment_me.*
import org.jetbrains.anko.support.v4.startActivity

class MeFragment : BaseFragment(), View.OnClickListener {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        return inflater.inflate(R.layout.fragment_me, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    private fun initView() {
        mUserNameTv.setOnClickListener(this)
        mUserIconIv.setOnClickListener(this)
        mSettingTv.setOnClickListener(this)
    }

    override fun onStart() {
        super.onStart()
        loadData()
    }

    private fun loadData() {
        if (isLogined()) {
            val icon = AppPrefsUtils.getString(ProviderConstant.KEY_USER_ICON)
            if (icon.isNotEmpty()) {
                mUserIconIv.loadUrl(icon)
            } else {
                mUserIconIv.setImageResource(R.drawable.icon_default_user)
            }
            mUserNameTv.text = AppPrefsUtils.getString(ProviderConstant.KEY_USER_NAME)
        } else {
            mUserIconIv.setImageResource(R.drawable.icon_default_user)
            mUserNameTv.text = getString(R.string.un_login_text)
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.mUserIconIv, R.id.mUserNameTv -> {
                if (isLogined()) {
                    startActivity<UserInfoActivity>()
                } else {
                    startActivity<LoginActivity>()
                }
            }
            R.id.mSettingTv->{
                startActivity<SettingActivity>()
            }
        }

    }

}